package com.example.demo.config;

import com.example.demo.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        
        try {
            String authHeader = request.getHeader("Authorization");
            logger.info("JWT Authorization header: " + authHeader);
            
            if (authHeader != null && authHeader.startsWith("Bearer ")) {
                String token = authHeader.substring(7);
                logger.info("Extracted token: " + token);
                
                boolean isValid = jwtUtils.validateToken(token);
                logger.info("Token validation result: " + isValid);
                
                if (isValid) {
                    Integer userId = jwtUtils.getUserIdFromToken(token);
                    logger.info("Extracted userId from token: " + userId);
                    
                    if (userId != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                        // 创建认证对象
                        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                                userId, null, new ArrayList<>());
                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        
                        // 设置安全上下文
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                        logger.info("Successfully set authentication for user: " + userId);
                    } else {
                        logger.warn("Failed to set authentication: userId is null or context already has authentication");
                    }
                } else {
                    logger.warn("Invalid token");
                }
            } else {
                logger.info("No Authorization header or not a Bearer token");
            }
        } catch (Exception e) {
            logger.error("无法设置用户认证: " + e.getMessage(), e);
        }
        
        // 继续过滤链
        chain.doFilter(request, response);
    }
} 